package com.zjdiepu.www.biz.third.net;

import java.net.SocketTimeoutException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

import javax.annotation.Resource;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.zjdiepu.www.base.core.BaseService;
import com.zjdiepu.www.base.lang.HttpClientException;
import com.zjdiepu.www.common.consts.ThirdService;
import com.zjdiepu.www.common.util.CollectionInitUtil;
import com.zjdiepu.www.commpent.HttpClient;
import com.zjdiepu.www.config.AliServiceProperty;
import com.zjdiepu.www.dao.third.JuheBrandMapper;
import com.zjdiepu.www.dao.third.JuheCarMapper;
import com.zjdiepu.www.dao.third.JuheSeriesMapper;
import com.zjdiepu.www.ibiz.third.net.ISynCarService;
import com.zjdiepu.www.model.third.dto.AliBrand;
import com.zjdiepu.www.model.third.dto.AliCar;
import com.zjdiepu.www.model.third.dto.AliSeries;
import com.zjdiepu.www.model.third.dto.JuheBrand;
import com.zjdiepu.www.model.third.dto.JuheCar;
import com.zjdiepu.www.model.third.dto.JuheSeries;
/**
 * 同步车型服务
 * @author xiongxiaotun
 * @date 2017年3月23日 下午4:10:44
 * @since v1.0.0
 * @update
 */
@Service
@Transactional(readOnly = true, propagation = Propagation.NOT_SUPPORTED, isolation = Isolation.READ_UNCOMMITTED, timeout = 60)
public class AliSynCarServiceImpl extends BaseService implements ISynCarService {
	private static final Logger logger = LoggerFactory.getLogger(AliSynCarServiceImpl.class);
	@Resource
	protected HttpClient httpClient;
	@Resource
	private AliServiceProperty aliServiceProperty;
	@Autowired
	private JuheBrandMapper juheBrandMapper;
	@Autowired
	private JuheSeriesMapper juheSeriesMapper;
	@Autowired
	private JuheCarMapper juheCarMapper;
	
	//品牌ID
	private AtomicReference<List<String>> brandIds = new AtomicReference<>();
	//遍历品牌序号
	public int index = 0;
	
	
	@Override
	public List<String> saveSynBrand() {
		String jsonBrandString = "";
		try {
			Map<String, String> brandParamMap = new HashMap<String, String>();
			jsonBrandString = httpClient.get(ThirdService.ALI_QUERY_ALL_CAR_BRAND, brandParamMap, getAliCommonHeaderMap(aliServiceProperty.getAppCode()));//品牌
			List<AliBrand> carBrands = commonProcessJsonResultFromAli(jsonBrandString, AliBrand.class);
			if(CollectionUtils.isNotEmpty(carBrands)) {
				if(CollectionUtils.isNotEmpty(carBrands)) {
					List<String> currentBrandIds = carBrands.stream().map(item -> item.getThirdId()).collect(Collectors.toList());
					brandIds.set(currentBrandIds);
					index = 0;
				}
			}
		} catch (SocketTimeoutException | HttpClientException e) {
			logger.info("saveSynBrand happen exception.responseJson: {}, exception : {}", jsonBrandString, e);
		} 
		return null;
	}
	
	@Override
	public void saveSynCar() {
		//当次请求的次数
		int count = 0;
		String jsonBrandString = "";
		List<String> currentBrandIds = brandIds.get();
//		if (CollectionUtils.isEmpty(currentBrandIds)) {
//			JuheBrandExt juheBrandExt = new JuheBrandExt();
//			juheBrandExt.setBaseWhere();
//			juheBrandExt.withOutPage();
//			List<JuheBrand> juheBrands = juheBrandMapper.selectByExt(juheBrandExt);
//			if(CollectionUtils.isNotEmpty(juheBrands)) {
//				currentBrandIds = juheBrands.stream().map(item -> item.getThirdId()).collect(Collectors.toList());
//				brandIds.set(currentBrandIds);
//				index = 0;
//			}
//		}
		if (CollectionUtils.isNotEmpty(currentBrandIds)) {
			while(index < currentBrandIds.size() && count < 30) {
				String jsonSeriesString = "";
				String companyId = "";
				try {
					Map<String, String> seriesParamMap = new HashMap<String, String>();
					companyId = currentBrandIds.get(index);
					seriesParamMap.put("parentid", companyId);
					++index;
					++count;
					jsonSeriesString = httpClient.get(ThirdService.ALI_QUERY_ALL_CAR_CARLIST_WITH_BRAND, seriesParamMap, getAliCommonHeaderMap(aliServiceProperty.getAppCode()));//车系
					List<String> brandIds = CollectionInitUtil.emptyList();
					List<AliBrand> brands = commonProcessJsonResultFromAli(jsonSeriesString, AliBrand.class);
					if(CollectionUtils.isNotEmpty(brands)) {
						brandIds = brands.stream().map(item -> item.getThirdId()).collect(Collectors.toList());
						List<JuheBrand> juheBrands = CollectionInitUtil.emptyList();
						for(AliBrand brand : brands) {
							JuheBrand juheBrand = new JuheBrand();
							juheBrand.initInsertData("aliyun", "阿里云市场");
							juheBrand.setThirdId(brand.getThirdId());
							juheBrand.setBigPpname(brand.getName());
							juheBrand.setPin(brand.getInitial());
							juheBrands.add(juheBrand);
							
							List<AliSeries> series = brand.getSeries();
							if(CollectionUtils.isNotEmpty(series)) {
								juheSeriesMapper.deleteByBrandId(brand.getThirdId());
								List<JuheSeries> juheSeries = CollectionInitUtil.emptyList();
								for(AliSeries sery : series) {
									JuheSeries juheSery = new JuheSeries();
									juheSery.initInsertData("aliyun", "阿里云市场");
									juheSery.setBrandId(sery.getParentId());//品牌ID(父ID)
									juheSery.setPpid(companyId); //公司ID
									juheSery.setPpname(brand.getName());
									juheSery.setXlid(sery.getThirdId());
									juheSery.setXlname(sery.getFullName());
									
									int countSery = juheSeriesMapper.updateBySeriesId(juheSery);
									if(countSery == 0) {
										juheSeries.add(juheSery);
									}
									
									List<AliCar> cars = sery.getCars();
									if(CollectionUtils.isNotEmpty(cars)) {
										juheCarMapper.deleteBySeriesId(sery.getThirdId());
										List<JuheCar> juheCars = CollectionInitUtil.emptyList();
										for(AliCar car : cars) {
											JuheCar juheCar = new JuheCar();
											juheCar.initInsertData("aliyun", "阿里云市场");
											juheCar.setSeriesId(car.getParentId());
											juheCar.setFbPyear(car.getYearType());
											juheCar.setCarId(car.getThirdId());
											juheCar.setCxname(brand.getName() + " " + sery.getFullName() + " " + car.getName());
											juheCar.setPyear(car.getYearType());
											String price = car.getPrice();
											if(StringUtils.isBlank(price)) {
												logger.debug("车辆市场价为空.id:{},seriesId:{},carId:{},price:{}",juheCar.getId(),juheCar.getSeriesId(),juheCar.getCarId(),juheCar.getPrice());
												juheCar.setPrice("暂无");
											} else {
												juheCar.setPrice(price);
											}
											
											int countCar = juheCarMapper.updateByCarId(juheCar);
											if(countCar == 0) {
												juheCars.add(juheCar);
											}
										}
										
										if(CollectionUtils.isNotEmpty(juheCars)) {
											juheCarMapper.insertBatch(juheCars); // 添加新数据
										}
									}
								}
								
								if(CollectionUtils.isNotEmpty(juheSeries)) {
									juheSeriesMapper.insertBatch(juheSeries); // 添加新数据
								}
							}
						}
						if(CollectionUtils.isNotEmpty(brandIds)) {
							juheBrandMapper.deleteByIds(brandIds);
						}
						if(CollectionUtils.isNotEmpty(juheBrands)) {
							juheBrandMapper.insertBatch(juheBrands); // 添加新数据
						}
					}
				} catch (SocketTimeoutException | HttpClientException e) {
					logger.info("saveSynBrand happen exception.index: {}, count: {}, companyId: {}, responseJson: {}, exception : {}", index, count, companyId, jsonBrandString, e);
				}
			}
		}
	}
	
	@Override
	public void saveSynCars() throws SocketTimeoutException, HttpClientException {
		
	}
	
	@Override
	public void saveSeries() throws SocketTimeoutException, HttpClientException {
		
	}
}
